<template>
  <div class="fenqy">
    <div class="contentTopTitle">
      <div class="fl">
        <div class="title">码号-月-分套餐</div>
      </div>
    </div>
    <div class="operation">
      <el-form :inline="true" :model="form" class="formList">
        <el-form-item label="选择区域">
          <dx-cascader :area_id.sync="form.areaId" />
        </el-form-item>
        <el-form-item label="账期">
          <el-date-picker
            v-model="form.acctYear"
            value-format="yyyy"
            type="year"
            placeholder="选择账期"
          ></el-date-picker>
          <!-- <el-date-picker
            v-model="form.startDate"
            value-format="yyyyMM"
            type="month"
            placeholder="选择开始月"
            @change="handle_selectEndMonth(form.startDate)"
          ></el-date-picker>
          <span>~</span>
          <el-date-picker
            v-model="form.endDate"
            value-format="yyyyMM"
            type="month"
            placeholder="选择结束月"
            @change="handle_selectEndMonth(form.endDate)"
          ></el-date-picker> -->
        </el-form-item>
        <el-form-item class="w5" label="存增量" label-width="80px">
          <el-select v-model="form.classType" clearable>
            <el-option label="全量" value="N"></el-option>
            <el-option label="存存量" value="CCL"></el-option>
            <el-option label="存增量" value="CZL"></el-option>
            <el-option label="增量" value="ZL"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户群" label-width="80px">
          <el-select v-model="form.level" clearable>
            <el-option
              v-for="(it, i) in level"
              :key="i"
              :label="it.indexName"
              :value="it.indexCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="锁定" label-width="60px">
          <el-select v-model="form.lock" clearable>
            <el-option
              v-for="(it, i) in lockList"
              :key="i"
              :label="it.label"
              :value="it.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="btns">
          <el-button size="small" type="primary" @click="submitHandle()"
            >查询</el-button
          >
          <el-button
            size="small"
            type="orange"
            @click="exportExcel(true)"
            style="margin-left: 20px"
            >批量导出</el-button
          >
          <el-button size="small" type="orange" @click="exportExcel(false)"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
      <!-- <el-checkbox-group style="margin:10px 0 10px 20px;" v-model="checkList" @change="checkedType">
        <el-checkbox
          v-for="(item,index) in form.checkedContent"
          :label="item.index"
          :key="index"
        >{{item.value}}</el-checkbox>
      </el-checkbox-group> -->
    </div>
    <p class="g-unit">收入: 元， 用户数: 户</p>
    <div class="tableBox">
      <el-table
        ref="table"
        border
        stripe
        v-loading="tableLoading"
        :data="tableData"
        style="width: 100%"
        class="tableTh28"
        height="73vh"
        :span-method="arraySpanMethod"
      >
        <!-- <el-table-column fixed label="项目" width="80" prop="proName"></el-table-column> -->
        <el-table-column
          fixed
          label="融合/单产品"
          width="120"
          prop="class1"
        ></el-table-column>
        <el-table-column
          fixed
          label="套餐等级"
          width="120"
          prop="indexname"
        ></el-table-column>
        <!-- <el-table-column fixed label="区域id" width="120" prop="areaId"></el-table-column>
        <el-table-column fixed label="区域名称" width="120" prop="areaName"></el-table-column>-->
        <el-table-column
          class-name="right-money"
          v-for="(item, index) in title"
          width="140"
          :key="index"
          :label="item.label"
        >
          <el-table-column
            width="110"
            :key="index"
            v-for="(it, index) in item.child"
            :label="it.label"
            :prop="it.value"
          ></el-table-column>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { $budgetAPI, $budget } from "@/api";
import { getSessionStorage } from "@/common/js/storage";
import { mergeSpan2 } from "@/utils/mixin.js";
import prefixAPI from "@/api/prefixAPI";
import { getCookie, setCookie } from "@/common/js/cookie";

let accountInfo = JSON.parse(getSessionStorage("accountInfo"));

export default {
  data() {
    return {
      tableLoading: false, //
      areaList: [],
      tableData: [],
      spanArr: "",
      form: {
        areaId: accountInfo.areaId,
        startDate: "",
        endDate: "",
        classType: "N",
        level: "",
        checkedContent: [
          { index: "1", value: "套餐数/用户数" },
          { index: "2", value: "收入" },
          { index: "3", value: "ARPU" },
          // { index: "4", value: "用户占比" },
          // { index: "5", value: "收入占比" },
        ],
        lock: "",
        acctYear: this.moment().format("yyyy"),
      },
      titleList: [],
      checkList: ["1", "2", "3"],
      level: [],
      lockList: [
        {
          label: "锁定",
          value: "1",
        },
        {
          label: "非锁定",
          value: "0",
        },
      ],
      title: [],
    };
  },
  created() {
    this.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
    // this.getMarketMonth();
    this.getData();
    this.getChoiceList();
  },
  methods: {
    vaildMonth(start, end) {
      let sYear = start.substr(0, 4),
        sMonth = start.substr(4, 2),
        eYear = end.substr(0, 4),
        eMonth = end.substr(4, 2),
        s = new Date(sYear + "-" + sMonth).getTime(),
        e = new Date(eYear + "-" + eMonth).getTime(),
        num;

      if (s < e) {
        num = true;
      } else {
        num = false;
      }
      if (!num) {
        this.$message({
          showClose: true,
          message: "开始日期不能大于结束日期",
          type: "warning",
        });
        this.form.endDate = "";
        return false;
      }
      if (start && end) {
        if (+eYear * 12 + +eMonth - (+sYear * 12 + +sMonth) > 12) {
          this.$message({
            showClose: true,
            message: "日期范围在1年内",
            type: "warning",
          });
          this.form.endDate = "";
          return false;
        }
      }
    },
    handle_selectEndMonth(val) {
      let startDate = this.form.startDate || "",
        endDate = this.form.endDate || "";

      startDate && endDate && this.vaildMonth(startDate, endDate);
    },
    areaChange() {},
    getChoiceList() {
      var that = this;

      $budgetAPI.getChoiceList({}, (res) => {
        that.level = res.content.cLevel;
      });
    },
    //分产品导出
    exportExcel(type) {
      let areaId = "";
      let month = "";
      if (this.form.areaId) {
        areaId = this.form.areaId;
      } else {
        areaId = this.accountInfo.areaId;
      }
      let startDate = this.form.startDate ? this.form.startDate : "";
      let endDate = this.form.endDate ? this.form.endDate : "";
      let classType = this.form.classType;
      let ids = this.checkList;
      let cLevel = this.form.level;
      let custLockFlg = this.form.lock;
      // if (!(startDate && endDate)) {
      //   this.$message({
      //     showClose: true,
      //     message: "请选择账期",
      //     type: "warning",
      //   });
      //   return;
      // }

      if (process.env.NODE_ENV == "development") {
        window.location.href =
          prefixAPI.loc +
          "/api/newIncomeTrack/exportIncomeDataSecondMealPartTwo?areaId=" +
          areaId +
          "&type=" +
          type +
          "&classType=" +
          classType +
          "&cLevel=" +
          cLevel +
          "&acctYear=" +
          this.form.acctYear +
          "&custLockFlg=" +
          custLockFlg +
          "&token=" +
          getCookie("token");
      } else if (process.env.NODE_ENV == "production") {
        window.location.href =
          prefixAPI.hp +
          "/api/newIncomeTrack/exportIncomeDataSecondMealPartTwo?areaId=" +
          areaId +
          "&type=" +
          type +
          "&classType=" +
          classType +
          "&cLevel=" +
          cLevel +
          "&custLockFlg=" +
          custLockFlg +
          "&acctYear=" +
          this.form.acctYear +
          "&token=" +
          getCookie("token");
      }
    },
    submitHandle() {
      this.getData();
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        return this.spanArr.length && this.spanArr[rowIndex][columnIndex];
      }
    },
    getData() {
      let that = this;
      let areaId = that.form.areaId
        ? that.form.areaId
        : that.accountInfo.areaId;
      let startDate = that.form.startDate ? that.form.startDate : "";
      let endDate = that.form.endDate ? that.form.endDate : "";
      let classType = that.form.classType;
      let afterInfo = [];
      let ids = that.checkList;

      that.title = Array.from(
        new Array(12),
        (item, value) =>
          (item = {
            label: value + 1 + "月",
            child: [
              {
                label: "套餐数/用户数",
                value:
                  "aft_" + (value + 1 < 10 ? "0" + (value + 1) : value + 1),
              },
              {
                label: "收入",
                value:
                  "income_" + (value + 1 < 10 ? "0" + (value + 1) : value + 1),
              },
              {
                label: "ARPU",
                value:
                  "arpu_" + (value + 1 < 10 ? "0" + (value + 1) : value + 1),
              },
            ],
          })
      );
      if (!that.form.acctYear) {
        this.$message({
          showClose: true,
          message: "请选择账期",
          type: "warning",
        });
        return;
      }
      that.tableLoading = true;
      console.log(ids);
      $budgetAPI.findIncomeSecondMealPart1(
        {
          areaId: areaId,
          classType: classType,
          cLevel: this.form.level,
          custLockFlg: this.form.lock,
          acctYear: that.form.acctYear,
        },
        (res) => {
          that.tableLoading = false;
          if (res.code == 0) {
            let content = res.content;
            // that.titleList = content.titles;
            // content.data.map((it) => {
            //   it.dataList.map((item, i) => {
            //     if(item.indexId == 'HP024020' || item.indexId == 'HP024019') {
            //         it[item.acctMonth + item.indexId] = item.indexValue != 0 ? item.indexValue + '%' : item.indexValue;
            //     } else {
            //         it[item.acctMonth + item.indexId] = item.indexValue;
            //     }

            //   });
            // });
            that.tableData = content;

            // afterInfo = that.afterData(content.titles);
            // console.log(afterInfo);
            // that.titleList = that.afterData(content.titles);

            that.spanArr = that.mergeSpan2(content, ["class1"]);

            that.$nextTick(() => {
              that.$refs.table.doLayout();
            });
          } else {
            that.alertError(res);
          }
        },
        (err) => {
          that.tableLoading = false;
        }
      );
    },

    //根据层级获取区域树
    getCompanyByLvl() {
      $budgetAPI.getCompanyByLvl(
        {
          lvl: this.accountInfo.areaLvl,
          areaId: this.accountInfo.areaId,
        },
        (res) => {
          let areaId = this.accountInfo.areaId;
          let areaName = this.accountInfo.areaName;
          if (res.code == 0) {
            for (let i = 0; i < res.content.length; i++) {
              if (res.content[i].areaId == areaId) {
                this.areaList = res.content;
                return;
              }
            }
            this.areaList = [{ areaId, areaName }, ...res.content];
          } else {
            this.alertError(res);
          }
        },
        (err) => {}
      );
    },
    formatDate: function (value) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y.toString() + MM.toString();
    },
    // getMaxAcctMonthByMealPart() {
    //   $budgetAPI.getMaxAcctMonthByMealPart(
    //     {},
    //     res => {
    //       if (res && res.code == 0) {
    //         this.form.month = res.content;
    //         this.getData();
    //       }
    //     },
    //     err => {}
    //   );
    // },
    getMarketMonth() {
      let areaId = this.form.areaId;
      let isMonthReport = 1;
      $budgetAPI.getIncomeSourceMonth(
        { areaId: areaId, isMonthReport: isMonthReport },
        (res) => {
          if (res || res.code == 0) {
            this.form.startDate = res.content.preSixMonth;
            this.form.endDate = res.content.maxAcctMonth;
            this.getData();
          }
        },
        (err) => {}
      );
    },
    mergeSpan2(tableData, arr) {
      let spanArr = new Array(tableData.length);
      for (let m = 0; m < spanArr.length; m++) {
        spanArr[m] = new Array(arr.length);
      }
      arr.forEach((ele, ind) => {
        let pos = null;
        tableData.forEach((item, index, self) => {
          if (index == 0) {
            spanArr[index][ind] = {
              rowspan: 1,
              colspan: 1,
            };
            pos = 0;
          } else {
            if (item[ele] === self[index - 1][ele]) {
              spanArr[pos][ind].rowspan += 1;
              spanArr[index][ind] = {
                rowspan: 0,
                colspan: 0,
              };
            } else {
              pos = index;
              spanArr[index][ind] = {
                rowspan: 1,
                colspan: 1,
              };
            }
          }
        });
      });
      return spanArr;
    },
    checkedType(val) {
      console.log(val);
      let that = this;
      that.checkList = val;
      //  that.form.checkedContent.push(it.)
    },
    afterData(val) {
      let tempArr = [];
      let afterData = [];
      for (let i = 0; i < val.length; i++) {
        if (tempArr.indexOf(val[i].acctMonth) === -1) {
          afterData.push({
            acctMonth: val[i].acctMonth,
            origin: [val[i]],
          });
          tempArr.push(val[i].acctMonth);
        } else {
          for (let j = 0; j < afterData.length; j++) {
            if (afterData[j].acctMonth == val[i].acctMonth) {
              afterData[j].origin.push(val[i]);
              break;
            }
          }
        }
      }
      return afterData;
    },
  },
};
</script>

<style lang="scss" scoped>
.formList .btns {
  width: 20%;
  /deep/ .el-form-item__content {
    width: 260px;
  }
}
.fenqy {
  /deep/ .el-table .cell {
    text-align: center;
  }
  // .daochu {
  //   float: right;
  //   .el-form-item__content {
  //     float: right;
  //     .el-button {
  //       float: right;
  //     }
  //   }
  // }
  // .el-form-item__content{
  //   float: right;
  // }
  .el-form-item.width50 {
    width: 40%;
    .el-form-item__content .el-input {
      width: 45%;
    }
  }

  .el-form-item.w5 {
    width: 25%;
  }
}
</style>
